﻿using AutoMapper;
using CommonType;
using MediatR;
using S_Examine.API.Application.Commands.AssessmentIndexCommand;
using S_Examine.Domains.Entity;
using S_Examine.Infrastructure.Interface;

namespace S_Examine.API.Application.CommandHandlers.AssessmentIndexHandler
{
	public class AssessmentIndexUpdateCommandHandler : IRequestHandler<AssessmentIndexUpdateCommand, ApiResule<int>>
	{
		private readonly IMapper _mapper;
		private readonly IAssessmentIndexRepository _assessmentIndexRepository;

		public AssessmentIndexUpdateCommandHandler(IAssessmentIndexRepository assessmentIndexRepository, IMapper mapper)
		{
			_assessmentIndexRepository = assessmentIndexRepository;
			_mapper = mapper;
		}

		public async Task<ApiResule<int>> Handle(AssessmentIndexUpdateCommand request, CancellationToken cancellationToken)
		{
			var assessment = _mapper.Map<AssessmentIndex>(request);

			var assessmentIndex = await _assessmentIndexRepository.GetByFuncAsync(x => x.IndexName == request.IndexName && x.Id != request.Id);

			if (assessmentIndex == null)
			{
				var result = await _assessmentIndexRepository.CreateAsync(assessment);

				if (result > 0)
				{
					return new ApiResule<int>
					{
						Code = 200,
						Msg = "成功",
						Result = result
					};
				}

				return new ApiResule<int>
				{
					Code = 201,
					Msg = "失败",
					Result = result
				};
			}

			return new ApiResule<int>
			{
				Code = 202,
				Msg = "指标名称已存在"
			};
		}
	}
}
